
package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/user")
public class UserServlet extends HttpServlet {

    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1、先读取出blogId，由于我们的blogId是通过query string 传递的，所以我们使用getParameter获取
        String blogId = req.getParameter("blogId");
        if(blogId == null || blogId.equals("")){
            //直接返回一个userId为0的对象，因为最终返回的是一个Json数据
            //此时也是返回json格式比较好，如果返回一个html,前端处理的时候还需要判断
            //这里new的user对象，是一个空的对象，也就满足了返回一个userId为0的对象
            String respJson = objectMapper.writeValueAsString(new User());
            resp.setContentType("application/json;charset=utf8");
            resp.getWriter().write(respJson);
            System.out.println("参数给定的blog为空");
            return;
        }
        //2.查询数据库，查询对应的Blog对象
        BlogDao blogDao = new BlogDao();
        Blog blog = blogDao.selectOne(Integer.parseInt(blogId));
        if(blog == null){
            String respJson = objectMapper.writeValueAsString(new User());
            resp.setContentType("application/json;charset=utf8");
            resp.getWriter().write(respJson);
            System.out.println("参数给定的blog不存在");
            return;
        }
        //3.根据blog中的userId，查询作者信息
        UserDao userDao = new UserDao();
        User user = userDao.selectUserById(blog.getUserId());
        if(user == null){
            String respJson = objectMapper.writeValueAsString(new User());
            resp.setContentType("application/json;charset=utf8");
            resp.getWriter().write(respJson);
            System.out.println("该博客对应的作者不存在");
        }
        //4.把user对象返回给页面
        String respJson = objectMapper.writeValueAsString(user);
        resp.getWriter().write(respJson);
        return;
    }
}
